import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// 导入全局css
import './assets/css/global.css'
import './assets/css/common.less'
import './assets/js/flexible.js'
import axios from 'axios';

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
import * as echarts from 'echarts';

Vue.prototype.$store = store;

axios.defaults.baseURL = "http://39.108.143.183:8181";
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.delete['Content-Type'] = 'application/x-www-form-urlencoded';
axios.interceptors.request.use(config => {
  // 为请求头添加Authorization字段为服务端返回的token
  config.headers.token = localStorage.getItem('token') ? localStorage.getItem('token') : '';
  // return config是固定用法 必须有返回值
  return config
});

axios.interceptors.response.use(response => {
  if (response.headers.authorization) {
    localStorage.setItem('token', response.headers.authorization)
    Vue.prototype.$store.commit("setToken", response.headers.authorization);
  }
  return response;
}, err => {
 
  if (err.response.data.code != 403) {
    return Promise.reject(err);
  }

  const config = err.config;
  const {
    __retryCount = 0, retryDelay = 1000, retryTimes = 2
  } = config;
  // 在请求对象上设置重试次数
  config.__retryCount = __retryCount;

  // 判断是否超过了重试次数
  if (__retryCount > retryTimes) {

    Vue.prototype.$message({
      showClose: true,
      message: "登录过期，请重新登录！",
      type: 'error'
    });
    router.replace({
      path: '/login'
    })

    return Promise.reject(err);
  }
  // 增加重试次数
  config.__retryCount++;
  // 延时处理

  // 延时promise
  const delay = new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, retryDelay);
  });

  // 重新发起请求
  return delay.then(function () {
    return axios(config);
  });
});
// 接口文件
import {
  portInterface
} from './assets/js/url.js'
Vue.prototype.$http = axios;

Vue.prototype.echarts = echarts;

Vue.prototype.portInterface = portInterface;



Vue.config.productionTip = false;

import JSEncrypt from 'jsencrypt';
Vue.prototype.$getRsaCode = function (str) { // 注册方法
  let pubKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwVcGn1jkijlJee+jmA7L
XijOEf5nmy/a3lGouHvgdphksXefemPLvUXNAyw2EE3PklT2S4PlFjRasijZtKjd
b3pAHVxX9wcPBk4ZbmnxMr4LTlfw/OwyepljLCyUsbPtoW+V6nfJJU1KUaXr5Jru
cjFpyok+7y7B8DZuy8BrXrP0ZDS9zAFtl6ci6WSvdrjnKDKHZL1792J4fCVesEXi
iZWOhaPt0dbjRLmK2UGdcorGHTdHOd/pufXQi42Yb2Ae2hh47vd9o1HavqRPeO++
4sFnSSU5WACu1XkZXvyJjRPFAmrx/XayrEWRZdzur8vLyQ00DEHDyUQdPEwiCbqR
8QIDAQAB
-----END PUBLIC KEY-----`; // ES6 模板字符串 引用 rsa 公钥
  let encryptStr = new JSEncrypt();
  encryptStr.setPublicKey(pubKey); // 设置 加密公钥
  let data = encryptStr.encrypt(str.toString()); // 进行加密
  return data;
}


new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')